/*
 * Copyright Hundsun Technologies Inc. All Rights Reserved.
 */

package service

import (
	"context"

	"hundsun.com/hsl/hschain/module"
	"hundsun.com/hsl/hschain/module/registry"
	"hundsun.com/hsl/hschain/p2p"
)

// GoroutineErrorWrapper goroutine错误包装
type GoroutineErrorWrapper struct {
	Error        error
	GoroutineTag string
}

type p2pModule struct {
	module.Adapter
	p2pInstance *P2p
}

func init() {
	p2p.Register("dht", NewModule)
}

// NewModule 新建一个p2p模块
func NewModule() module.Module {
	m := &p2pModule{}

	moduleStartupFunc := func(startedInterestedModules map[string][]*registry.ModRegKV) error {
		p2pCtx, p2pCtxCancelFun := context.WithCancel(m.RootCtx)
		p := NewP2p(p2pCtx, m.Config, p2pCtxCancelFun, m.Log)
		err := p.Init()
		if err != nil {
			return err
		}
		p.StartP2p()
		m.p2pInstance = p
		m.Log.Infof("module started:%s", m.Config.ModuleID)
		return nil
	}

	m.Init(module.P2pModuleName, m.GetInterestedModules(), moduleStartupFunc)
	return m
}

//GetInterestedModules GetInterestedModules
func (p *p2pModule) GetInterestedModules() []string {
	return nil
}

//Shutdown Shutdown
func (p *p2pModule) Shutdown() (module.Status, error) {

	p.Log.Infof("shutdown %s", p.Config.ModuleID)
	p.RootCtxCancelFunc()
	p.p2pInstance.CloseP2p()
	p.Status = module.StatusDown
	return p.Status, nil
}
